#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "socket.h"
#include "wizchip_conf.h"
#include "httpclient.h"



#define onenet_id       "1050928010"               	        /* your onenet device ID */
#define apikey          "j=4xBH0JKRFqcDOXWdHe0uUTJ8g="      /* your onenet master apikey */
#define data_id         "test"                              /* Data name of the device */ 
#define test_massge1    "Hello WIZnet W5100S/W5500."        /* test data stream 1 */
#define test_massge2    "Thsi is a upload test."            /* test data stream 2 */

/**
 * @brief   OneNET HTTP POST :  Request package combination package.
 * @param   pkt:    Array cache for grouping packages
 * @param   key:    User master APIkey
 * @param   devid:  Device ID
 * @param   dsid:   Date ID
 * @param   val:    Date
 * @return  Packet length.
*/
uint32_t HTTP_PostPkt(uint8_t *pkt, uint8_t *key, uint8_t *devid, uint8_t *dsid, uint8_t *val)
{
	uint8_t dataBuf[100] = {0};
	uint8_t lenBuf[10] = {0};
	*pkt = 0;

	sprintf( dataBuf, ",;%s,%s", dsid, val);    										/*采用分割字符串格式:type = 5*/
	sprintf(lenBuf, "%d", strlen(dataBuf));

	strcat(pkt, "POST /devices/");
	strcat(pkt, devid);
	strcat(pkt, "/datapoints?type=5 HTTP/1.1\r\n");

	strcat(pkt, "api-key:");
	strcat(pkt, key);
	strcat(pkt, "\r\n");  

	strcat(pkt, "Host:api.heclouds.com\r\n");

	strcat(pkt, "Content-Length:");
	strcat(pkt, lenBuf);
	strcat(pkt, "\r\n\r\n");

	strcat(pkt, dataBuf);
    
	return strlen(pkt);
}


/**
 * @brief   HTTP Client upload data OneNET stream test.
 * @param   sn:         socket number
 * @param   buf:        array cache
 * @param   destip:     destion ip
 * @param   destport:   destion port
 * @return  none.   
*/
void do_http_client(uint8_t sn, uint8_t* buf, uint8_t* destip, uint16_t destport)
{
    uint16_t local_port = 50000;
    uint16_t len;
    static uint8_t testsel_flag = 0;
    uint8_t* testmassage;
    switch (getSn_SR(sn))
    {
    case SOCK_INIT:
        connect(sn, destip, destport);
        break;
    case SOCK_ESTABLISHED:
        if(testsel_flag)testmassage=test_massge1;
        else testmassage=test_massge2;
        len = HTTP_PostPkt(buf, apikey, onenet_id, data_id, testmassage);
        send(sn, buf, len);
        testsel_flag=!testsel_flag;
        break;
    case SOCK_CLOSE_WAIT:
        close(sn);
        break;
    case SOCK_CLOSED:
        close(sn);
        socket(sn, Sn_MR_TCP, local_port, 0x00);
        break;
    default:
        break;
    }
}